<script lang="ts" setup>
import type { FormInstance } from "element-plus";

const emit = defineEmits(["submitSuccess"]);

const visible = defineModel<boolean>("visible");

const rules = ref({
    min: [{ required: true, message: "请输入起始杆号", trigger: "blur" }]
});

const formRef = ref<FormInstance>();

const formData = ref({
    min: "",
    max: ""
});

const validate = () => {
    return new Promise((resolve) => {
        formRef.value
            ?.validate()
            .then((res) => {
                resolve(res);
            })
            .catch(() => {
                resolve(false);
            });
    });
};

const submit = async () => {
    const valid = await validate();
    if (!valid) return;
    try {
        const { success, message } = await numberClient.batchAddNumbersApi({
            min: formData.value.min,
            max: formData.value.max || ""
        });
        if (!success) {
            ElMessage.error(message || "新增失败");
        } else {
            ElMessage.success("新增成功");
            emit("submitSuccess");
            visible.value = false;
        }
    } catch (error: any) {
        ElMessage.error(error.message || "新增失败");
    }
};

const getMaxNumber = async () => {
    const { success, data } = await numberClient.maxNumberApi();
    if (!success) return;
    if (data) {
        formData.value.min = (data.num - 0 + 1).toString();
    }
};

watch(
    () => visible.value,
    (newVal) => {
        if (newVal) {
            formData.value.max = "";
            formData.value.min = "";
            formRef.value?.resetFields();
            getMaxNumber();
        }
    }
);
</script>
<template>
    <el-dialog
        v-model="visible"
        title="新增"
        draggable
        width="500"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
        <el-form :model="formData" :rules="rules" label-position="top" ref="formRef" size="small">
            <el-form-item label="起始杆号" prop="min">
                <el-input v-model="formData.min" placeholder="请输入起始杆号" />
            </el-form-item>
            <el-form-item label="截止杆号">
                <el-input v-model="formData.max" placeholder="请输入截止杆号" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="visible = false">关闭</el-button>
                <el-button type="primary" @click="submit">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style lang="scss" scoped>
.data-form {
}
</style>
